package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.IPage;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
@Transactional
public class OrderServiceimpl implements OrderService {
    @Autowired
    private OrderMapper ordermapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private OrderdetailMapper orderdetailmapper;
    @Autowired
   private AddressBookMapper addressbookmapper;
@Autowired
private ShoppingcartMapper shoppingcartmapper;
@Autowired
private UserMapper usermapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        //处理各种业务异常(购物车和地址)
        AddressBook addressBook=addressbookmapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
          throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long id= BaseContext.getCurrentId();
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(id);
        List<ShoppingCart> list=shoppingcartmapper.list(shoppingCart);
        if(list==null||list.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);

        }

//订单表插入一条数据
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(id);
        orders.setPayStatus(1);


        ordermapper.insert(orders);

        //向订单明细表插入多条数据
        List<OrderDetail> orderDetailList=new ArrayList<>();
for(ShoppingCart cart:list){
     OrderDetail orderDetail=new OrderDetail();
     BeanUtils.copyProperties(cart,orderDetail);
     orderDetail.setOrderId(orders.getId());
     orderDetailList.add(orderDetail);
}
orderdetailmapper.insert(orderDetailList);

        //清空购物车
shoppingcartmapper.deleteall(id);
        //封装结果
OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
        .id(orders.getId())
        .orderTime(orders.getOrderTime())
        .orderNumber(orders.getNumber())
        .orderAmount(orders.getAmount())
        .build();

          Map map= new HashMap<>();
          map.put("type",1);
          map.put("orderId",orders.getId());
          map.put("content","新订单来了 "+orders.getPhone());
          log.info("来单提醒");
        String json=JSON.toJSONString(map);
          webSocketServer.sendToAllClient(json);


        return orderSubmitVO;
    }
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = usermapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = ordermapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordermapper.update(orders);
    }

    @Override
    public OrderVO getorderdetail(Long id) {
        OrderVO orderVO =new OrderVO();
        Orders orders=ordermapper.selectbyid(id);
        List<OrderDetail>list=orderdetailmapper.selectByOrderId(id);
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(list);
        orderVO.setAddress(getaddress(orders));
        return orderVO;

    }

    @Override
    public PageResult historypage(int page, int pageSize, Integer status) {
        PageHelper.startPage(page, pageSize);
        Long id=BaseContext.getCurrentId();
        OrdersPageQueryDTO ordersPageQueryDTO=new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(id);
        Page<Orders> pages=ordermapper.historypage(ordersPageQueryDTO);
        List<OrderVO> list=new ArrayList<>();
        if (pages != null && pages.getTotal() > 0) {
            for (Orders orders : pages) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderdetailmapper.selectByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }

        return new PageResult(pages.getTotal(),list);
    }

    @Override
    public void cancelorder(Long id) {
        Orders orders=ordermapper.selectbyid(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders1 = new Orders();
        orders1.setId(orders.getId());

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordermapper.update(orders);
    }

    @Override
    public void openanotherorder(Long id) {
        //复制订单信息，只是添加到购物车中，并不是真正的订单



        //复制订单信息，转化为购物车对象
        Orders orders=ordermapper.selectbyid(id);
        List<OrderDetail> list=orderdetailmapper.selectByOrderId(id);
        ShoppingCart shoppingCart=new ShoppingCart();

//先清空购物车
        shoppingcartmapper.deleteall(orders.getId());

        if(list!=null&&list.size()>0){
        for(OrderDetail orderDetail:list){
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(orders.getUserId());
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingcartmapper.addshoppingcart(shoppingCart);
        }
        }

    }

    @Override
    public PageResult ordermanage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> page=ordermapper.historypage(ordersPageQueryDTO);

        List<OrderVO> orderVOList = getOrderVOList(page);
        return  new PageResult(page.getTotal(),orderVOList);
    }

    private List<OrderVO> getOrderVOList(Page<Orders> page) {
        // 需要返回订单菜品信息，自定义OrderVO响应结果
        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();
        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);

                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);

                orderVO.setAddress((getaddress(orders)));
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderdetailmapper.selectByOrderId(orders.getId());
        StringBuilder sb = new StringBuilder();
        for (OrderDetail orderDetail : orderDetailList) {
            sb.append(orderDetail.getName());
            sb.append("*");
            sb.append(orderDetail.getNumber());
            sb.append(";");
        }



        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
//        List<String> orderDishList = orderDetailList.stream().map(x -> {
//            String orderDish = x.getName() + "*" + x.getNumber() + ";";
//            return orderDish;
//        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return sb.toString();
    }

    private  String getaddress(Orders orders) {
        StringBuilder s=new StringBuilder();
        AddressBook addressBook=addressbookmapper.getdefaultById(orders.getUserId());
        if (addressBook != null) {
            // 再判断每个属性是否为 null，避免拼接出 "null" 字符串
            if (addressBook.getProvinceName() != null) {
                s.append(addressBook.getProvinceName());
            }
            if (addressBook.getCityName() != null) {
                s.append(addressBook.getCityName());
            }
            if (addressBook.getDistrictName() != null) {
                s.append(addressBook.getDistrictName());
            }
            if (addressBook.getDetail() != null) {
                s.append(addressBook.getDetail());
            }
            return s.toString();

        }else {
            return  s.length() > 0 ? s.toString() : "暂无默认地址";

        }
    }

    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = ordermapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = ordermapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = ordermapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();

        ordermapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders ordersDB = ordermapper.selectbyid(ordersRejectionDTO.getId());
        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orders.setCancelReason("商家取消");
        orders.setCancelTime(LocalDateTime.now());

        ordermapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        ordermapper.update(orders);
    }
    public void delivery(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordermapper.selectbyid(id);

        // 校验订单是否存在，并且状态为3
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        ordermapper.update(orders);
    }
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = ordermapper.selectbyid(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        ordermapper.update(orders);
    }

    @Override
    public void cuidan(Long id) {
        Orders ordersDB = ordermapper.selectbyid(id);
        if (ordersDB == null||!ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Map map=new HashMap<>();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","用户催单了");
        String js= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(js);
    }
}
